package cn.pugle.base.thread;

import java.util.Scanner;

/**
 * @author tzp
 * @date 2017/11/17
 */
public class ShutdownTest {
    static volatile boolean keepRunning = true;

    public static void main(String[] args) {
        test3();
    }

    /**
     * 测试1. 当ctrl-c时,shudownHook里的线程被要求等待mainThread. 非要下面循环睡那10s出来了, 才能结束
     */
    public static void test1() {
        final Thread mainThread = Thread.currentThread();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("hooking running");
            keepRunning = false;
            try {
                mainThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));
        for (int i = 0; i < 10 && keepRunning; ++i) {

            try {
                Thread.sleep(10000);
                System.out.println("10s");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试2. 当ctrl-c时,shudownHook里的线程. 先interrupt mainThread. 下面循环会收到这个异常, 打印退出, 不用等那10s.
     */
    public static void test2() {
        final Thread mainThread = Thread.currentThread();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("hooking running");
            keepRunning = false;
            try {
                mainThread.interrupt();
                mainThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));

        for (int i = 0; i < 10 && keepRunning; ++i) {

            try {
                Thread.sleep(10000);
                System.out.println("10s");
            } catch (InterruptedException e) {
                System.out.println("I has been interrupted, " + e.getMessage());
            }
        }
    }

    /**
     * 测试3. 当ctrl-c时,shudownHook里的线程interrupt mainThread.
     * 但mainThread没有调用可以抛出InterruptedException的方法, 也没有自己检测InterruptedException,
     * 主要是scanner.nextLine没有处理interrupt的flag.
     * 所以之后也join上了, 必须等待阻塞的scanner.nextLine()返回后才能退出
     * see https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
     */
    public static void test3() {
        final Thread mainThread = Thread.currentThread();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("hooking running");
            keepRunning = false;
            try {
                mainThread.interrupt();
                mainThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));

        for (int i = 0; i < 10 && keepRunning; ++i) {
            Scanner scanner = new Scanner(System.in);
            String s = scanner.nextLine();
            System.out.println(s);
        }
    }
}
